/**
 * Created by 李一方 on 2015/3/6.
 */

//引入需要的dojo模块
dojo.require('dojo.String');

//定义全局变量
var indexURL = 'page-1.html';
var forumURL = 'forum.html?id=${id}';
var topicURL = 'topic.html?id=${id}';
var pageType = 'index.html' || 'fourum.html' || 'topic.html';
var idFromUrl = null;

//定义需要的方法
function parseCurrentUrl() {
    var currentUrl = window.document.URL;
    if (0 < currentUrl.indexOf('index.html')) pageType = 'index.html';
    if (0 < currentUrl.indexOf('forum.html')) pageType = 'forum.html';
    if (0 < currentUrl.indexOf('topic.html')) pageType = 'topic.html';
    idFromUrl = currentUrl.substr(currentUrl.indexOf('=') + 1);
}

//动态显示当前论坛或者话题的名字
function showName() {
    if (pageType == 'forum.html') dojo.byId('forumName').innerHTML = forumURL[idFromUrl].name;
    if (pageType == 'topic.html') dojo.byId('topicName').innerHTML = forumURL[idFromUrl].name;
}

//填充UL下面的列表。如果是index页面，则列出所有的论坛；如果是forum页面，则列出所有话题
function createNodeList() {
    if (pageType == 'topic.html') return;
    var urlDom, urlFormat, nodes;
    if (pageType == 'index.html') {
        urlDom = dogo.byId('forumList');
        urlFormat = forumURL;
        nodes = forums;
    }
    if (pageType == 'topic.html') {
        ulDom = dojo.byId('topicList');
        urlFormat = topicURL;
        nodes = topics;
    }

    dojo.forEach(nodes, function (item) {
        if (pageType == 'index.html' || idFromUrl == item.parent) {
//            计算被一个话题的URL地址
            var itemURL = dojo.string.substitute(urlFormat, {'id': item.id});

            dojo.create('li', {innerHTML: item.name, onclick: function () {
                window.location.href = itemURL;
            }}, urlDom, 'last');
        }
    });

    function createBreadcrumbs() {
        if (pageType == 'index.html') return;
        var breadcrumbs = dojo.byId('breadcrumbs');
        dojo.create('a', {innerHTML: '首页', href: indexURL}, breadcrumbs, 'last');
        if (pageType == 'forum.html') {
            dojo.create('textNode', {innerHTML: '>'}, breadcrumbs, 'last');
            dojo.create('textNode', {innerHTML: forums[idFromUrl].name}, breadcrumbs, 'last');
        }
        if (pageType == 'topoc.html') {
            dojo.create('textNode', {innerHTML: '>'}, breadcrumbs, 'last');
            dojo.create('textNode', {innerHTML: forums[topics[idFromUrl].parent].name,
                href: dojo.string.substitute(forumURL, {'id': topics[idFromUrl].parent})}, 'last');
            dojo.create('textNode', {innerHTML: '>'}, breadcrumbs, 'last');
            dojo.create('textNode', {innerHTML: topics[idFromUrl].name}, breadcrumbs, 'last');
        }
    }

    dojo.addOnLoad(function () {
        parseCurrentUrl();
        showName();
        createNodeList();
        createBreadcrumbs();
    });
}
